package br.com.fpf.pontoapp.ws.impl;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.select.Elements;

import br.com.fpf.pontoapp.model.dto.Batida;
import br.com.fpf.pontoapp.model.dto.InfoDTO;

public class Conection {
	static String conteudoDoPost;
	static String request = "http://www.ahgora.com.br/batidas/entrar/ajax";
	static String urlBatidas = "http://www.ahgora.com.br/batidas/ver/10-2013";
	static URL url;
	static HttpURLConnection connection;
	static String headerName = null;
	static String sessionCookie = null;
	static List<Batida> batidas = new ArrayList<Batida>();
	static InfoDTO info = new InfoDTO();
	static String nome;

	public static InfoDTO ResultBatidas(String matricula, String senha) {
		try {
			conteudoDoPost = "dados[empresa]=a665612&dados[matricula]="
					+ matricula + "&dados[senha]=" + senha;
			// Create connection
			url = new URL(request);
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");

			connection.setRequestProperty("Content-Length",
					"" + Integer.toString(conteudoDoPost.getBytes().length));
			connection.setUseCaches(false);
			connection.setDoInput(true);
			connection.setDoOutput(true);

			// Send request
			DataOutputStream wr = new DataOutputStream(
					connection.getOutputStream());
			wr.writeBytes(conteudoDoPost);
			wr.flush();
			wr.close();

			// Get Response
			InputStream is = connection.getInputStream();
			BufferedReader rd = new BufferedReader(new InputStreamReader(is));
			String line;
			StringBuffer response = new StringBuffer();
			while ((line = rd.readLine()) != null) {
				response.append(line);
				response.append('\r');
			}
			rd.close();
			System.out.println(response.toString());

			for (int i = 1; (headerName = connection.getHeaderFieldKey(i)) != null; i++) {
				if (headerName.equalsIgnoreCase("Set-Cookie")) {
					if (sessionCookie == "") {
						sessionCookie = connection.getHeaderField(i);
					} else {
						sessionCookie += "; " + connection.getHeaderField(i);
					}
				}
			}

			url = new URL(urlBatidas);
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestProperty("Cookie", sessionCookie);

			// Pega a resposta
			is = connection.getInputStream();
			rd = new BufferedReader(new InputStreamReader(is));
			response = new StringBuffer();
			while ((line = rd.readLine()) != null) {
				response.append(line);
				response.append('\r');
			}
			rd.close();
			parser(response.toString());

		} catch (Exception e) {
			e.printStackTrace();
		} finally {

			if (connection != null) {
				connection.disconnect();
			}
		}
		info.setBatidas(batidas);
		info.setNome(nome);
		return info;
	}

	private static void parser(String html) {
		org.jsoup.nodes.Document docSoup = Jsoup.parse(html);
		Batida batida;
		nome = retornaNome(docSoup.select("div.float_r").text());
		Elements elements = docSoup.select("tbody tr");

		for (int i = 0; i < 31; i++) {
			batida = new Batida();
			Elements elements2 = elements.get(i).select("td[rowspan]");
			batida.setBatidas(elements2.get(2).text());
			batida.setDia(elements2.get(0).text());
			if (!batida.getBatidas().equals("")) {
				batidas.add(batida);
			}

		}
	}

	private static String retornaNome(String text) {
		int pos = text.indexOf(" | Imprimir | sair");

		return text.substring(0, pos);
	}
}
